'use strict';

var _ = require('underscore');
var Promise = require('bluebird');

module.exports = function(sequelize, DataTypes) {
  //文章表
  var Article = sequelize.define('Article', {
    title: {
      type: DataTypes.STRING,
      allowNull: false,
      comment: '标题',
      validate: {
        notEmpty: {
          msg: '标题不允许为空'
        },
        len: {
          args: [1, 255],
          msg: '标题长度必须在1至255字节之间'
        },
      },
    },
    deliverTime: {
      type: DataTypes.DATE,
      comment: '发表时间',
    },
    summary: {
      type: DataTypes.STRING(5000),
      comment: '摘要',
      validate: {
        len: {
          args: [0, 5000],
          msg: '摘要长度必须在1至5000字节之间'
        },
      },
    },
    keyword: {
      type: DataTypes.STRING,
      comment: '关键词',
      validate: {
        len: {
          args: [0, 255],
          msg: '关键词长度必须在1至255字节之间'
        },
      },
    },
    content: {
      type: DataTypes.TEXT('long'),
      comment: '正文内容',
    },
    TemplateId: {
      type: DataTypes.INTEGER,
      comment: '文章模板'
    },
    MainPictureId: {
      type: DataTypes.INTEGER,
      comment: '主题图'
    },
    isShow: {
      type: DataTypes.BOOLEAN,
      comment: '显示'
    },
    readCount: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '阅读数'
    }
  }, {
    charset: 'utf8',
    classMethods: {
      associate: function(models) {
        Article.belongsTo(models.Category, {
          constraints: false
        });
      },
      fetch: function(op) {
        return this.findAll(_.extend({
          order: [
            ['deliverTime', 'DESC'],
            ['createdAt', 'DESC']
          ]
        }, op || {}));
      },
      //获取指定分类下的所有文章(包括子分类)
      fetchByCategoryCode: function(categoryCode) {
        return this.findAll({
          where: {
            order: [
              ['deliverTime', 'DESC'],
              ['createdAt', 'DESC']
            ]
          },
          include: [{
            association: this.associations.Category,
            where: {
              code: {
                $like: categoryCode + '%'
              }
            }
          }]
        });
      },
      //获取文章分页数据
      fetchPage: function(option) {
        //page:页数:获取记录数,size:获取记录数
        //categoryCode:分类编号，search:搜索关键字，where:其他条件
        var where = option.where || {};

        if (option.search) {
          where = _.extend(where, {
            $or: [{
              title: { $like: '%' + option.search + '%' }
            }, {
              keyword: { $like: '%' + option.search + '%' }
            }, {
              summary: { $like: '%' + option.search + '%' }
            }, {
              content: { $like: '%' + option.search + '%' }
            }]
          });
        }
        var offset = (option.page >= 1 && option.size > 0) ? (option.page - 1) * option.size : 0;
        var param = _.extend({
          where: where,
          order: [
            ['deliverTime', 'DESC'],
            ['createdAt', 'DESC']
          ],
          offset: offset,
          limit: option.size
        }, option.op || {});

        if (option.categoryCode) {
          param.include = [{
            association: this.associations.Category,
            where: {
              code: option.categoryCode
            }
          }];
        }
        if (option.page <= 1) {
          return this.findAndCountAll(param);
        } else {
          return this.findAll(param)
            .then(function(_art) {
              return { rows: _art };
            });
        }
      }
    }
  });

  return Article;
};
